package com.sgl.config.quarz;



import com.sgl.entity.AcceptPayOrder;
import com.sgl.entity.MybatisParamVo;
import com.sgl.entity.OrderHistory;
import com.sgl.service.AcceptPayOrderService;
import com.sgl.service.DictService;
import com.sgl.service.OrderService;
import com.sgl.util.HttpUtil;
import com.sgl.util.PageBean;
import com.sgl.util.StringSingUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 定义任务类
 */


@DisallowConcurrentExecution //禁止并发执行
@Service
public class CheckCallBack implements Job, ApplicationRunner {

    @Autowired
    DictService dictService;

    @Autowired
    OrderService orderService;

    private static final Log log = LogFactory.getLog(CheckCallBack.class);


   private  ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);
    @Autowired
    AcceptPayOrderService acceptPayOrderService;

    /**
     * 任务被触发时所执行的方法
     * 根据 状态为2 次数 小于10 的符合条件查询订单 然后将查出来的订单 进行重新回调
     * 如果 接收 到crm系统的确认信息 之后 将订单状态修改为已处理 否则
     * 订单重新回调的count次数-1 如果次数 减到0以下 之后 将状态 改为 无法处理需要人工介入的状态
     *
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String key=dictService.findByKeywords("secretKey").getValue();
        String payNotifyurl=dictService.findByKeywords("payNotifyurl").getValue();
        String merchantId=dictService.findByKeywords("merchantId").getValue();
        String account=dictService.findByKeywords("account").getValue();
        HashMap<String, Object> param = new HashMap<String, Object>();
        param.put("status", 2);
        param.put("count",10);//这个地方可以更改 次数
        PageBean<OrderHistory> pageBean = new PageBean<>();
        pageBean.setParam(param);
        pageBean.setPageSize(100);
        //List<AcceptPayOrder> list = acceptPayOrderService.findList(pageBean);

        //查找 没有回调成功的订单信息  条件 status=2 and count>0
        List<OrderHistory> list = orderService.findList(pageBean);
        log.info("开始查找没有回调成功的订单信息========>一共找到"+list.size() +"条数据");
        //todo 剩余次数是0次的时候修改为 调用超出次数 停止回调
        Integer countRe=0;
        if (list.size()>0){
           for (OrderHistory order:list){
                //通知crm系统
                log.info("通知crm系统");
                LinkedHashMap<String, String> parameter = new LinkedHashMap<>();

                parameter.put("pay_secid",merchantId);
                parameter.put("pay_orderid",order.getMerOrderId());
                parameter.put("pay_currency","USD");
                parameter.put("pay_amount",order.getNoticeAmount());
                parameter.put("pay_status","OK");

                String sign = StringSingUtils.getSign2(parameter, key);
                parameter.put("pay_sign", sign);

                try{

                    String result = HttpUtil.doPost(payNotifyurl, parameter);

                    if (result.indexOf("OK")>-1|| result.indexOf("200")>-1) {
                        PageBean<OrderHistory> pageBean2 = new PageBean<>();
                        HashMap<String, Object> hashMap = new HashMap<>();
                        hashMap.put("merOrderId", order.getMerOrderId());
                        pageBean2.setParam(hashMap);
                        pageBean2.setPageSize(100);

                        List<OrderHistory> orderHistorys = orderService.findOrderByMerOrderId(pageBean2);
                        MybatisParamVo<OrderHistory> paramVo = new MybatisParamVo<>();
                        paramVo.setParams(orderHistorys);
                        paramVo.setStatus(1);
                        //将这类订单状态改为 回调成功
                        Integer integer = orderService.changeStatusByParam(paramVo);
                       if (integer>0){
                           log.info("=============acceptorderservice订单改为回调成功=============");
                           AcceptPayOrder payOrder = acceptPayOrderService.getPayOrderByOrderId(order.getMerOrderId());
                           if (payOrder==null){
                               log.error("订单信息不存在");

                           }
                           Integer integer1 = acceptPayOrderService.changeStatiusByid(payOrder.getId());
                           if (integer1>0){
                               log.info("成功修改"+order.getMerOrderId()+"为完成订单");
                           }
                           countRe++;
                       }
                    }else {
                        log.info("本次失败！");

                        //TODO 回调失败更新count次数 count--
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }


                if (order.getCount()<0){
                    log.info("==============此订单回调次数达到上限： "+order.getMerOrderId()+" 不再回调 转人工处理==============");
                    //将状态改为3 回调超出次数 需要人工介入
                    MybatisParamVo<OrderHistory> vo = new MybatisParamVo<>();
                    vo.setStatus(3);
                    ArrayList<OrderHistory> params = new ArrayList<>();
                    params.add(order);
                    vo.setParams(params);
                    //将订单改为三
                    Integer integer = orderService.changeStatusByParam(vo);
                    log.info("==============更改了： "+integer+" 条订单 为处理失败订单 需要人工处理==============");
                    //
                }
            }
            log.info("==============更改了： "+countRe+" 条订单为处理成功==============");

        }else {
            log.info("==============没有需要重新回调的订单===================");
            return;
        }


    }

    @Override
    public void run(ApplicationArguments args) throws Exception {

    }
}
